package com.fingard.dsp.bank.directbank.crbc01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalanceCheck;
import com.fingard.dsp.bank.reqrespobj.balancecheck.ReqBalCheckQry;
import com.fingard.dsp.bank.reqrespobj.balancecheck.RetAtsBalCheckQry;
import com.fingard.dsp.bank.reqrespobj.balancecheck.detail.RetAtsBalCheckDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CRBC01BalanceCheck extends CRBC01Base implements IBalanceCheck {
    @Override
    public RetAtsBalCheckQry d_7508_BalCheck(ReqBalCheckQry p_req7508) throws Exception {
        RetAtsBalCheckQry retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
        retAts.writeStart();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();
            CRBC01Header bankHeader = new CRBC01Header();
            bankHeader.tranCode = "140002";
            bankHeader.tranTime = new SimpleDateFormat("yyyyMM").parse(p_req7508.yearMonth);
            Calendar tmpClnderFrom = Calendar.getInstance();
            Calendar tmpClndrStepTo = Calendar.getInstance();
            tmpClnderFrom.setTime(bankHeader.tranTime);
            tmpClndrStepTo.setTime(bankHeader.tranTime);
            tmpClnderFrom.set(Calendar.DAY_OF_MONTH, 1);
            tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
            if (DateHelper.compareDay(new Date(), tmpClndrStepTo.getTime()) == -1) {
                tmpClndrStepTo.setTime(new Date());
            }
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("BODY");
            xmlWriter.writeElementString("ACCOUNT_NO", p_req7508.actNum);
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpAbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpAbMsg);

                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_CODE");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_MSG");
                    if (isActiveRetCode(tmpRetCode)) {
                        String state = tmpBkReader.getFirstText("/CRBANK/BODY/STATE");
                        if ("1".equals(state)) {
                            return d_140004_BalCheck(p_req7508);
                        } else {
                            return d_140001_BalCheck(p_req7508);
                        }
                    } else {
                        retAts.writeRespCode(tmpRetCode);
                        retAts.writeRespInfo(tmpRetMsg);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpAbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAtsBalCheckQry d_140001_BalCheck(ReqBalCheckQry p_req7508) throws Exception {
        RetAtsBalCheckQry retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
        retAts.writeStart();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();
            CRBC01Header bankHeader = new CRBC01Header();
            bankHeader.tranCode = "140001";
            bankHeader.tranTime = new SimpleDateFormat("yyyyMM").parse(p_req7508.yearMonth);
            Calendar tmpClnderFrom = Calendar.getInstance();
            Calendar tmpClndrStepTo = Calendar.getInstance();
            tmpClnderFrom.setTime(bankHeader.tranTime);
            tmpClndrStepTo.setTime(bankHeader.tranTime);
            tmpClnderFrom.set(Calendar.DAY_OF_MONTH, 1);
            tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
            if (DateHelper.compareDay(new Date(), tmpClndrStepTo.getTime()) == -1) {
                tmpClndrStepTo.setTime(new Date());
            }
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("BODY");
            xmlWriter.writeElementString("SEQ_NO", p_req7508.reqHeader.transSeqID);
            String contactName = getBankConfig().getValueAsString("contactName");
            if (StringHelper.isNullOrEmpty(contactName)) {
                retAts.writeRespCode("0");
                retAts.writeRespInfo("未配置联系人姓名,请检查config.xml中'contactName'配置项");
                retAts.writeEnd();
                return retAts;
            }
            xmlWriter.writeElementString("ACCOUNT_CHECK_NAME", contactName);
            String contactCellPhone = getBankConfig().getValueAsString("contactCellPhone");
            if (StringHelper.hasAnyChar(contactCellPhone)) {
                if (contactCellPhone.length() != 11) {
                    retAts.writeRespCode("0");
                    retAts.writeRespInfo("联系人电话长度不对,请检查config.xml中'contactCellPhone'配置项");
                    retAts.writeEnd();
                    return retAts;
                }
            } else {
                retAts.writeRespCode("0");
                retAts.writeRespInfo("未配置联系人电话,请检查config.xml中'contactCellPhone'配置项");
                retAts.writeEnd();
                return retAts;
            }
            xmlWriter.writeElementString("ACCOUNT_CHECK_PHONE", contactCellPhone);
            xmlWriter.writeStartElement("ARRAY");
            xmlWriter.writeStartElement("STRUCT");
            xmlWriter.writeElementString("ACCOUNT_NO", p_req7508.actNum);
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpAbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpAbMsg);

                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_CODE");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_MSG");
                    if (isActiveRetCode(tmpRetCode)) {
                        return d_140004_BalCheck(p_req7508);
                    } else {
                        retAts.writeRespCode(tmpRetCode);
                        retAts.writeRespInfo(tmpRetMsg);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpAbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    public RetAtsBalCheckQry d_140004_BalCheck(ReqBalCheckQry p_req7508) throws Exception {
        RetAtsBalCheckQry retAts = new RetAtsBalCheckQry(p_req7508.reqHeader, p_req7508.actNum);
        retAts.writeStart();
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();
            CRBC01Header bankHeader = new CRBC01Header();
            bankHeader.tranCode = "140004";
            bankHeader.tranTime = new SimpleDateFormat("yyyyMM").parse(p_req7508.yearMonth);
            Calendar tmpClnderFrom = Calendar.getInstance();
            Calendar tmpClndrStepTo = Calendar.getInstance();
            tmpClnderFrom.setTime(bankHeader.tranTime);
            tmpClndrStepTo.setTime(bankHeader.tranTime);
            tmpClnderFrom.set(Calendar.DAY_OF_MONTH, 1);
            tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
            if (DateHelper.compareDay(new Date(), tmpClndrStepTo.getTime()) == -1) {
                tmpClndrStepTo.setTime(new Date());
            }
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("BODY");
            xmlWriter.writeElementString("SEQ_NO", p_req7508.reqHeader.reqSeqID);
            xmlWriter.writeElementString("ACCOUNT_NO", p_req7508.actNum);
            xmlWriter.writeElementString("BEGINDATE",Format.Date8Format.format(tmpClnderFrom.getTime()));
            xmlWriter.writeElementString("ENDDATE", Format.Date8Format.format(tmpClndrStepTo.getTime()));
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpAbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpAbMsg);

                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_CODE");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CRBANK/HEAD/RET_MSG");
                    if (isActiveRetCode(tmpRetCode)) {
                        RetAtsBalCheckDetail tmpRetDetail = new RetAtsBalCheckDetail();
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.respInfo = tmpRetMsg;
                        while (tmpBkReader.read("/CRBANK/BODY/ARRAY/STRUCT")) {
                            tmpRetDetail.statementNumber = tmpBkReader.readedXElement.getSingleText("COMPARENO");//对账单编号
                            tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("ACCNO");//账号
                            tmpRetDetail.actName = tmpBkReader.readedXElement.getSingleText("ACCNAME");//户名
                            tmpRetDetail.yearMonth = p_req7508.yearMonth;//对账日期
                            String fixDate = tmpBkReader.readedXElement.getSingleText("BEGINDATE");
                            if (!StringHelper.isNullOrEmpty(fixDate) && fixDate.length() == 8) {
                                tmpRetDetail.fixDate = fixDate.substring(0, 4) + "-" + fixDate.substring(4, 6) + "-" + fixDate.substring(6, 8);
                            }
                            String balDate = tmpBkReader.readedXElement.getSingleText("STOPDATE");
                            if (!StringHelper.isNullOrEmpty(balDate) && balDate.length() == 8) {
                                tmpRetDetail.balDate = balDate.substring(0, 4) + "-" + balDate.substring(4, 6) + "-" + balDate.substring(6, 8);
                            }
                            //银行对账状态：0-相符 1-不相符 2-忽略 3-调节后相符 4-未对账 5-强制忽略 7-纸质回收成功
                            String dzFlag = tmpBkReader.readedXElement.getSingleText("STATE");
                            //资金对账状态：1未对账,2平(余额相符),3不平(余额不符),6纸质回收成功,7调节相符,8忽略,9强制忽略
                            String atsFlag = "";
                            if ("0".equals(dzFlag)) {
                                atsFlag = "2";
                            } else if ("1".equals(dzFlag)) {
                                atsFlag = "3";
                            } else if ("2".equals(dzFlag)) {
                                atsFlag = "8";
                            } else if ("3".equals(dzFlag)) {
                                atsFlag = "7";
                            } else if ("4".equals(dzFlag)) {
                                atsFlag = "1";
                            } else if ("5".equals(dzFlag)) {
                                atsFlag = "9";
                            } else if ("7".equals(dzFlag)) {
                                atsFlag = "6";
                            }
                            tmpRetDetail.dzFlag = atsFlag;
                            String tmpBalance = "";
                            if (tmpBkReader.readedXElement.getSingleText("BALANCE") != null) {
                                tmpBalance = tmpBkReader.readedXElement.getSingleText("BALANCE").trim();
                            }
                            if (tmpBalance.length() > 0) {
                                tmpRetDetail.actBal = tmpBalance;
                            }
                            tmpRetDetail.dateFrom = tmpBkReader.readedXElement.getSingleText("BEGINDATE");
                            tmpRetDetail.dateTo = tmpBkReader.readedXElement.getSingleText("ENDDATE");
                            String deadDate = tmpBkReader.readedXElement.getSingleText("STOPDATE");
                            if (!StringHelper.isNullOrEmpty(deadDate) && deadDate.length() == 8) {
                                tmpRetDetail.deadDate = deadDate.substring(0, 4) + "-" + deadDate.substring(4, 6) + "-" + deadDate.substring(6, 8);
                            }
                            tmpRetDetail.contactName = tmpBkReader.readedXElement.getSingleText("NAME");
                            tmpRetDetail.contactPost = tmpBkReader.readedXElement.getSingleText("POST");
                            tmpRetDetail.telNbr = tmpBkReader.readedXElement.getSingleText("TELEPHONE");
                            tmpRetDetail.mobile = tmpBkReader.readedXElement.getSingleText("PHONE");
                            tmpRetDetail.email = tmpBkReader.readedXElement.getSingleText("EMAIL");

                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpRetMsg);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpAbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }
}
